import os, asyncio, logging
import sqlite3


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def dict_factory(cursor,row):
    '''
    Let the selected result from sqlite3 become a dict
    '''
    d={}
    for dex,col in enumerate(cursor.description):
        d[col[0]]=row[dex]
    return d

con=sqlite3.connect(os.path.join(BASE_DIR, 'database.db'))
con.row_factory=dict_factory  # Let the selected result from sqlite3 is dict instead of tuple


def log(sql, args=()):
    logging.info('SQL: %s' % sql)


def try_create_table():

    user_table = '''
        CREATE TABLE IF NOT EXISTS users
        (
            user_id VARCHAR(50),
            email VARCHAR(50),
            nickname VARCHAR(30),
            password VARCHAR(40),
            balance INT,
            status INT,
            create_at INT,
            PRIMARY KEY (user_id)
        )
        '''
    order_table = '''
        CREATE TABLE IF NOT EXISTS orders
        (
            order_id INT PRIMARY KEY,
            prepaid_for VARCHAR(50),
            payor VARCHAR(50),
            card_key VARCHAR(50),
            amount INT,
            friend_id VARCHAR(50),
            create_at INT
        )
        '''
    card_table = '''
        CREATE TABLE IF NOT EXISTS prepaidCards
        (
            card_key VARCHAR(50) PRIMARY KEY,
            amount INT,
            create_at INT,
            status INT
        )
        '''
    cur=con.cursor()
    cur.execute(user_table)
    cur.execute(order_table)
    cur.execute(card_table)
    cur.execute('INSERT OR IGNORE INTO users(user_id, nickname, balance, status) VALUES("17090120377", "root", 0, 100)')
    con.commit()
    cur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
    values = cur.fetchall()
    print(values)
    cur.close()


try_create_table()


#@asyncio.coroutine
async def select(sql, args, size=None):
    log(sql, args)
    #connect db
    #con=sqlite3.connect('text.db')
    #con.row_factory=dict_factory  # Let the selected result from sqlite3 is dict instead of tuple
    cur=con.cursor()
    cur.execute(sql,args or ())
    if size:
        rs=cur.fetchmany(size)
    else:
        rs=cur.fetchall()

    logging.info('rows returned: %s' % len(rs))
    cur.close()
    #con.close()
    return rs

#@asyncio.coroutine
async def execute(sql, args, autocommit=True):
    log(sql)
    #connect db
    #con=sqlite3.connect('text.db')
    cur=con.cursor()
    cur.execute(sql,args)
    con.commit()
    affected=cur.rowcount
    cur.close()
    #con.close()
    return affected

def create_args_string(num):
    L = []
    for n in range(num):
        L.append('?')
    return ', '.join(L)


class Field(object):
    '''
    the base class for fields of db
    '''
    def __init__(self, name, column_type, primary_key, default):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default

    def __str__(self):
        return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)

class StringField(Field):

    def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):
        super().__init__(name, ddl, primary_key, default)

class BooleanField(Field):

    def __init__(self, name=None, default=False):
        super().__init__(name, 'boolean', False, default)

class IntegerField(Field):

    def __init__(self, name=None, primary_key=False, default=0):
        super().__init__(name, 'bigint', primary_key, default)

class FloatField(Field):

    def __init__(self, name=None, primary_key=False, default=0.0):
        super().__init__(name, 'real', primary_key, default)

class TextField(Field):

    def __init__(self, name=None, default=None):
        super().__init__(name, 'text', False, default)



class ModelMetaclass(type):

    def __new__(cls, name, bases, attrs):
        if name=='Model':  #exclude Model class self
            return type.__new__(cls, name, bases, attrs)
        
        tableName = attrs.get('__table__', None) or name
        mappings = dict()
        fields = []
        primaryKey = None
        for k, v in attrs.items():
            if isinstance(v, Field):
                logging.info('  found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
                if v.primary_key:  # find primary key
                    if primaryKey:
                        raise StandardError('Duplicate primary key for field: %s' % k)
                    primaryKey = k
                else:
                    fields.append(k)
        if not primaryKey:
            raise StandardError('Primary key not found.')
        for k in mappings.keys():
            attrs.pop(k)  # Remove attribute from class in order to avoid name confusion
        escaped_fields = list(map(lambda f: '`%s`' % f, fields))
        attrs['__mappings__'] = mappings # Preserving mapping relations between attributes and columns
        attrs['__table__'] = tableName
        attrs['__primary_key__'] = primaryKey #  primary key name
        attrs['__fields__'] = fields # columns' name except primary key
        attrs['__select__'] = 'select `%s`, %s from `%s`' % (primaryKey, ', '.join(escaped_fields), tableName)
        attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1))
        attrs['__update__'] = 'update `%s` set %s where `%s`=?' % (tableName, ', '.join(map(lambda f: '`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey)
        attrs['__delete__'] = 'delete from `%s` where `%s`=?' % (tableName, primaryKey)
        return type.__new__(cls, name, bases, attrs)

class Model(dict, metaclass=ModelMetaclass):

    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

    def getValue(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default  # default value can be a method, get its return when run here
                logging.debug('using default value for %s: %s' % (key, str(value)))
                setattr(self, key, value)
        return value

    @classmethod
    #@asyncio.coroutine
    async def findAll(cls, where=None, args=None, **kw):
        '''
        find objects by where clause. 
        '''
        sql = [cls.__select__]
        if where:
            sql.append('where')
            sql.append(where)
        if args is None:
            args = []
        orderBy = kw.get('orderBy', None)
        if orderBy:
            sql.append('order by')
            sql.append(orderBy)
        limit = kw.get('limit', None)
        if limit is not None:
            sql.append('limit')
            if isinstance(limit, int):
                sql.append('?')
                args.append(limit)
            elif isinstance(limit, tuple) and len(limit) == 2:
                sql.append('?, ?')
                args.extend(limit)
            else:
                raise ValueError('Invalid limit value: %s' % str(limit))
        rs = await select(' '.join(sql), args)
        return [cls(**r) for r in rs]

    @classmethod
    #@asyncio.coroutine
    async def findNumber(cls, selectField, where=None, args=None):
        '''
        find number by select and where. 
        '''
        sql = ['select %s _num_ from `%s`' % (selectField, cls.__table__)]
        if where:
            sql.append('where')
            sql.append(where)
        rs = await select(' '.join(sql), args, 1)
        if len(rs) == 0:
            return None
        return rs[0]['_num_']

    @classmethod
    #@asyncio.coroutine
    async def find(cls, pk):
        '''
        find object by primary key.
        '''
        rs = await select('%s where `%s`=?' % (cls.__select__, cls.__primary_key__), [pk], 1)
        if len(rs) == 0:
            return None
        return cls(**rs[0])

    #@asyncio.coroutine
    async def save(self):
        args = list(map(self.getValueOrDefault, self.__fields__))
        args.append(self.getValueOrDefault(self.__primary_key__))
        rows = await execute(self.__insert__, args)
        if rows != 1:
            logging.warn('failed to insert record: affected rows: %s' % rows)

    #@asyncio.coroutine
    async def update(self):
        args = list(map(self.getValue, self.__fields__))
        args.append(self.getValue(self.__primary_key__))
        rows = await execute(self.__update__, args)
        if rows != 1:
            logging.warn('failed to update by primary key: affected rows: %s' % rows)

    #@asyncio.coroutine
    async def remove(self):
        args = [self.getValue(self.__primary_key__)]
        rows = await execute(self.__delete__, args)
        if rows != 1:
            logging.warn('failed to remove by primary key: affected rows: %s' % rows)
